import type {
  Klass,
  LexicalCommand,
  LexicalEditor,
  TextNode,
} from 'lexical'
import {
  $getNodeByKey,
  $getSelection,
  $isDecoratorNode,
  $isNodeSelection,
  COMMAND_PRIORITY_LOW,
  KEY_BACKSPACE_COMMAND,
  KEY_DELETE_COMMAND,
} from 'lexical'
import type { EntityMatch } from '@lexical/text'
import {
  mergeRegister,
} from '@lexical/utils'
import { registerLexicalTextEntity } from './utils'
import { CustomTextNode } from './custom-text/node'
import { useLexicalComposer } from 'lexical-vue'
import { onMounted,onUnmounted } from 'vue'

export function useLexicalTextEntity<T extends TextNode>(
  getMatch: (text: string) => null | EntityMatch,
  targetNode: Klass<T>,
  createNode: (textNode: CustomTextNode) => T,
) {
  const editor= useLexicalComposer();
  let unregisterListener: () => void;
  onMounted(()=> {
    unregisterListener = mergeRegister(...registerLexicalTextEntity(editor, getMatch, targetNode, createNode));
  })

  onUnmounted(()=> {
    unregisterListener?.()
  })

}